package com.yc.cloud.common.config;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author: 杨智杰
 * @date: 2021/8/12 15:02
 */
@Component
public class ServerConfig implements ApplicationListener<WebServerInitializedEvent> {

    private final static String HTTP = "http:";

    private int serverPort;

    @Value("${server.servlet.context-path:}")
    private String contextPath;

    public String getSwaggerUrl() {
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        if (ObjectUtil.isNull(address)) {
            return "获取swagger地址失败!";
        } else {
            return new StringBuilder().append(HTTP).append(StrUtil.SLASH).append(StrUtil.SLASH)
                    .append(address.getHostAddress()).append(StrUtil.COLON).append(serverPort)
                    .append(contextPath).append(StrUtil.SLASH).append("doc.html").toString();
        }
    }

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        this.serverPort = event.getWebServer().getPort();
    }

}
